package csu.softwaremetric.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
public class CodeLineMetricService {
    public JSONObject getCodeLine(String path)
    {
        int totalCount = 0;
        int commentCount = 0;
        int blankCount = 0;
        int commentBegin = -1;
        JSONObject jsonObject = new JSONObject();
        try (BufferedReader br = Files.newBufferedReader(Paths.get(path))){
            String line;
            while ((line = br.readLine()) != null) {
                totalCount++;
                if(line.contains("//"))
                {
                    commentCount++;
                } else if (line.isEmpty()) {
                    blankCount++;
                }
                else if (line.contains("/*"))
                {
                    if(commentBegin == -1){
                        commentBegin = totalCount;}
                } else if (line.contains("*/")) {
                    if(commentBegin != -1)
                    {
                        commentCount += (totalCount - commentBegin + 1);
                        commentBegin = -1;
                    }
                }
            }
            jsonObject.put("STATUS", "SUCCESS");
            jsonObject.put("MSG", "成功");
            jsonObject.put("TotalLine", totalCount);
            jsonObject.put("blankLine", blankCount);
            jsonObject.put("commentLine", commentCount);
            return jsonObject;
        }
        catch (IOException e) {
            jsonObject.put("STATUS", "FAILURE");
            jsonObject.put("MSG", "文件不存在");
            return jsonObject;
        }
    }
}
